#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    QStringList args = QApplication::arguments();

    port = "/dev/ttyUSB0";
    baud = 115200;

    for(int n = 0; n < args.count(); n++) {
        if(QString(args[n]).compare("-b") == 0)
            baud = QString(args[++n]).toInt();
        if(QString(args[n]).compare("-p") == 0)
            port = QString(args[++n]);
    }

    ui->setupUi(this);
    mainLayout = new QVBoxLayout();

    serialConsole = new SerialConsole(this);
    serialThread = new SerialThread(serialConsole, this);

    mainLayout->addWidget(serialConsole);
    ui->centralWidget->setLayout(mainLayout);

    termPrefs = new TermPrefs(serialConsole);

    QToolBar *portToolbar = this->addToolBar(tr("Port"));
    cbPort.clear();
    portToolbar->addWidget(&cbPort);
    portToolbar->setLayoutDirection(Qt::RightToLeft);
    cbPort.addItem(port);
    cbPort.setEnabled(false); // turn off temporarily

    connect(ui->actionOpenPort,SIGNAL(toggled(bool)), this,SLOT(actionButtonOpenPort(bool)));
    connect(ui->actionPreferences,SIGNAL(triggered()), this, SLOT(actionButtonPreferences()));
    connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(actionExit()));
    connect(qApp,SIGNAL(aboutToQuit()),this,SLOT(actionExit()));

    serialPort = new SerialPort();
    this->serialPort->init(port, baud);
    serialThread->startup(this->serialPort);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::actionButtonOpenPort(bool enabled)
{
    if(enabled) {
        this->serialThread->init(port, baud);
        serialThread->startup(this->serialPort);
        if(this->serialThread->open() != true) {
            ui->actionOpenPort->setChecked(false);
            QMessageBox::information(
                this,tr("Open Error"),tr("Could not open port ")+port,
                QMessageBox::Ok);
        }
    }
    else
        this->serialThread->close();
}

void MainWindow::actionButtonPreferences()
{
    termPrefs->showDialog();
}

void MainWindow::actionExit()
{
    this->serialThread->close();
    this->serialThread->stop();
    qApp->exit(0);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(event->type()) {}; // silence compiler
    actionExit();
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
